package java_thinking.unit_21._21_15;

import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Desc:   15.5 基于 AtomicInteger 实现的随机数生成器
 * @author: cww
 * @DateTime: 2019-06-28 23:43
 */

public class AtomicPseudoRandom extends Random {
    private AtomicInteger seed;
    public AtomicPseudoRandom( AtomicInteger seed1) {
        this.seed = seed1;
    }

    public int nextInt_1(int n) {
        while (true) {
            int s = seed.get();
            int nextSeed = nextInt(s);
            if (seed.compareAndSet(s,nextSeed)) {
                int remainder = s % n;
                return remainder > 0 ? remainder : remainder;
            }
        }
    }
}
